<template>
  <div class="reader" :style="styleInfo.style">
    <!-- 工具 -->
    <div class="tools">
      <div
        class="tool"
        v-for="(item, index) in tools"
        :key="index"
        @click="chooseStyle(item)"
      >
        {{ item.name }}
      </div>

      <div class="adjust">
        <div class="ad-btn small" @click="adjustFontSize">小</div>
        <div class="ad-btn big" @click="adjustFontSize('plus')">大</div>
      </div>

      <div class="tool" @click="scrollToBottom">直达底部</div>
    </div>
    <div class="reader-container" v-if="chapter">
      <!-- <div class="chapter-title">
        <h1>{{ chapter.title }}</h1>
      </div> -->
      <div class="chapter-content" :style="{ fontSize: fontSize + 'px' }">
        <div v-html="chapter.content"></div>
      </div>
    </div>

    <div class="chapter-nav" v-if="chapter">
      <div v-if="chapter.prev" @click="goToChapter(chapter.prev?.id)">
        上一章：<span class="text">{{ chapter.prev.title }}</span>
      </div>
      <div v-if="chapter.next" @click="goToChapter(chapter.next?.id)">
        下一章：<span class="text">{{ chapter.next.title }}</span>
      </div>
    </div>
    <div class="tools">
      <div class="tool" @click="scrollToTop">直达顶部</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { getChapterContent } from "@/api/books";

const route = useRoute();
const router = useRouter();
const chapter = ref(null);

// 加载章节内容
const loadChapter = async () => {
  try {
    const response = await getChapterContent(
      route.params.id,
      route.params.chapter
    );
    chapter.value = response.data;
  } catch (error) {
    console.error("获取章节内容失败:", error);
  }
};

// 跳转到指定章节
const goToChapter = (chapterId) => {
  if (chapterId !== undefined) {
    router.push(`/reader/${route.params.id}/${chapterId}`);
    loadChapter();
    this.reload();
  }
};

// 返回书籍详情页
const goToDetail = () => {
  router.push(`/book/${route.params.id}`);
};

onMounted(() => {
  // 加载样式
  const styleInfo = localStorage.getItem("styleInfo");
  if (styleInfo) {
    chooseStyle(JSON.parse(styleInfo));
  }
  // 加载字体大小
  let fontSizeStorage = localStorage.getItem("fontSize");
  if (fontSizeStorage) {
    // 最大25 最小12
    if (fontSizeStorage > 25) {
      fontSizeStorage = 25;
    } else if (fontSizeStorage < 12) {
      fontSizeStorage = 12;
    }
    fontSize.value = Number(fontSizeStorage);
  }

  loadChapter();
});

// 样式工具
const tools = ref([
  {
    name: "默认",
    style: {
      color: "#000",
      background: "#e7e4d5",
    },
  },
  {
    name: "明亮",
    style: {
      color: "#000000",
      background: "#ffffff",
    },
  },
  {
    name: "夜间",
    style: {
      color: "rgb(102, 102, 102)",
      background: "#000000",
    },
  },
]);
const styleInfo = ref(tools.value[0]);
const chooseStyle = (item) => {
  styleInfo.value = item;
  // 保存至本地
  localStorage.setItem("styleInfo", JSON.stringify(item));
};
// 调整字体大小
const fontSize = ref(18);
const adjustFontSize = (type) => {
  // 最大25 最小12
  if (type === "plus") {
    if (fontSize.value >= 25) {
      return;
    }
    fontSize.value += 1;
  } else {
    if (fontSize.value <= 12) {
      return;
    }
    fontSize.value -= 1;
  }
  // 保存至本地
  localStorage.setItem("fontSize", fontSize.value);
};

// 平滑滚动函数
const smoothScroll = (targetPosition) => {
  const startPosition = window.pageYOffset;
  const distance = targetPosition - startPosition;
  const duration = 500; // 滚动持续时间（毫秒）
  let startTime = null;

  const animation = (currentTime) => {
    if (startTime === null) startTime = currentTime;
    const timeElapsed = currentTime - startTime;
    const progress = Math.min(timeElapsed / duration, 1);

    // 使用缓动函数使滚动更自然
    const easeInOutQuad = (t) => (t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t);
    const position = startPosition + distance * easeInOutQuad(progress);

    window.scrollTo(0, position);

    if (progress < 1) {
      // 检查是否支持requestAnimationFrame
      if (window.requestAnimationFrame) {
        window.requestAnimationFrame(animation);
      } else {
        // 降级处理
        setTimeout(() => animation(Date.now()), 16);
      }
    }
  };

  // 检查浏览器支持
  if (window.requestAnimationFrame) {
    window.requestAnimationFrame(animation);
  } else {
    // 降级处理
    setTimeout(() => animation(Date.now()), 16);
  }
};

// 滚动到顶部
const scrollToTop = () => {
  // 检查是否支持原生平滑滚动
  if ("scrollBehavior" in document.documentElement.style) {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  } else {
    smoothScroll(0);
  }
};

// 滚动到底部
const scrollToBottom = () => {
  const targetPosition =
    Math.max(
      document.documentElement.scrollHeight,
      document.body.scrollHeight
    ) - window.innerHeight;

  // 检查是否支持原生平滑滚动
  if ("scrollBehavior" in document.documentElement.style) {
    window.scrollTo({
      top: targetPosition,
      behavior: "smooth",
    });
  } else {
    smoothScroll(targetPosition);
  }
};
</script>

<style lang="scss" scoped>
.reader {
  min-height: 100vh;
  background-color: #e7e4d5;
  box-sizing: border-box;
  .reader-container {
    padding: 14px;

    .chapter-title {
      text-align: center;
      margin-bottom: 14px;

      h1 {
        font-size: 18px;
        font-weight: 700;
        margin: 0;
      }
    }
  }

  .chapter-nav {
    font-size: 16px;
    padding: 14px;
    .text {
      // color: $main_color;
    }
  }
}

::v-deep .chapter-content {
  font-size: 16px;
  h1,
  h2,
  h3,
  h4,
  h5,
  h6 {
    margin: 0;
    padding: 0;
    font-weight: 700;
    text-align: center !important;
  }
  p {
    text-indent: 32px;
  }
  img {
    width: 80%;
    margin: 0 auto;
    display: block;
    border-radius: 4px;
  }
}

.tools {
  padding: 4px 14px;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .tool {
    min-width: 40px;
    padding: 0 4px;
    text-align: center;
    display: inline-block;
    box-sizing: border-box;
    border: 1px solid #ccc;
    border-radius: 4px;
    margin: 0 4px;
    height: 26px;
    line-height: 26px;
  }
  .adjust {
    display: flex;
    align-items: center;
    border: 1px solid #ccc;
    width: 80px;
    height: 26px;
    line-height: 26px;
    border-radius: 4px;
    box-sizing: border-box;
    margin: 0 4px;
    .ad-btn {
      width: 50%;
      text-align: center;
    }
    .small {
      border-right: 1px solid #ccc;
    }
    .big {
      font-size: 15px;
    }
  }
}
</style>
